#include <bits/stdc++.h>

using namespace std;

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool isBalanced(TreeNode* root) {
        bool balance = true;
        depth(root, balance);
        return balance;
    }

private:
    int depth(TreeNode *root, bool& balance) {
        if (!balance || root == nullptr) {
            return 0;
        }
        int ld = depth(root->left, balance) + 1;
        int rd = depth(root->right, balance) + 1;
        if (balance) {
            balance = abs(ld - rd) <= 1;
        }
        return max(ld, rd);
    }
};
